﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
using Tiens.NotificationHub.Abstractions.Store;
using Tiens.NotificationHub.Services;
using Tiens.NotificationHub.Core.Options;
using Tiens.NotificationHub.Core.Services;
using Tiens.NotificationHub.RedisStore;

namespace Tiens.NotificationHub.Core.Extensions
{
    public static class RedisStoreServiceCollectionExtensions
    {
        public static IServiceCollection AddRedisAppConnectionManager(this IServiceCollection services,IConfiguration configuration)
        {
            services.AddOptions<RedisStoreOptions>()
                .Configure(configuration.GetSection(nameof(RedisStoreOptions)).Bind);

            services.AddSingleton<ConnectionMultiplexer>(sp =>
            {
                var options = sp.GetRequiredService<IOptions<RedisStoreOptions>>().Value;
                var redisConfiguration = ConfigurationOptions.Parse(options.ConnectionString, true);
                redisConfiguration.ResolveDns = true;
                redisConfiguration.Password = options.Password;
                //当是集群，存在多个节点时
                //ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("server1:6379,server2:6379");

                return ConnectionMultiplexer.Connect(redisConfiguration);
            });

            services.TryAddScoped<IAppConnectionStore, AppConnectionStore>();
            services.TryAddScoped<IAppConnectionManager, InRedisAppConnectionManager>();

            return services;
        }


        public static IServiceCollection AddInMemoryAppConnectionManager(this IServiceCollection services)
        {
            services.TryAddScoped<IAppConnectionManager, InMemoryAppConnectionManager>();

            return services;
        }
    }
}
